package com.da.javatest.thread.juc.semaphore;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author chenlida
 * @date 2020/7/11 22:30
 *
 * public void acquire() throws InterruptedException这个方法会响应线程中断，主线程中对t2、t3发送中断信号之后，
 * acquire()方法会触发InterruptedException异常，t2、t3最终没有获取到许可，但是他们都执行了finally中的释放许可的操作，
 * 最后导致许可数量变为了2，导致许可数量增加了
 */
public class Semaphore2 {
    private static Semaphore semaphore = new Semaphore(1);

    public static class MyThread extends Thread {
        public MyThread(String name) {
            super.setName(name);
        }

        @Override
        public void run() {
            Thread thread = Thread.currentThread();
            try {
                semaphore.acquire();
                System.out.println(thread.getName() + "获得许可,当前可用许可为:" + semaphore.availablePermits());
                TimeUnit.SECONDS.sleep(5);
                System.out.println(thread.getName() + "运行结束");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                semaphore.release();
            }
            System.out.println(thread.getName() + "当前可用许可为:" + semaphore.availablePermits());
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MyThread t1 = new MyThread("t1");
        t1.start();
        TimeUnit.SECONDS.sleep(1);
        MyThread t2 = new MyThread("t2");
        t2.start();
        TimeUnit.SECONDS.sleep(1);
        MyThread t3 = new MyThread("t3");
        t3.start();

        // t2,t3发出中断
        t2.interrupt();
        t3.interrupt();
    }
}
